package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.dao.DishFlavorMapper;
import com.itheima.dao.DishMapper;
import com.itheima.domain.Dish;
import com.itheima.domain.DishFlavor;
import com.itheima.dto.DishDto;
import com.itheima.service.DishFlavorService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class DishFlavorServiceImpl
        extends ServiceImpl<DishFlavorMapper, DishFlavor>
        implements DishFlavorService {


    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    //根据id查询菜品数据(还有口味数据)
    @Override
    public DishDto getDishDtoById(Long id) {

        //查询菜品数据
        Dish dish = dishMapper.selectById(id);
        //查询菜品对应的口味数据
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DishFlavor::getDishId, dish.getId());
        List<DishFlavor> list = dishFlavorMapper.selectList(wrapper);
        //把数据赋值给DTO
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish, dishDto);
        //设置口味
        dishDto.setFlavors(list);
        //返回
        return dishDto;
    }

    //保存菜品,包括口味
    @Override
    public void updateDish(DishDto dishDto) {
        //修改菜品数据
        dishMapper.updateById(dishDto);

        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        //取出id
        Long id = dishDto.getId();
        wrapper.eq(DishFlavor::getDishId,id);
        //删除数据
        dishFlavorMapper.delete(wrapper);
        //修改菜品口味数据

        List<DishFlavor> flavors = dishDto.getFlavors();
        //判断口味是否为空
        if( flavors != null && flavors.size() > 0){
            //遍历,修改值
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(id);
                dishFlavorMapper.insert(flavor);
            }
        }


    }

}

